package com.bluexmicro.module_componment.file

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bluexmicro.module_componment.R
import com.bluexmicro.module_componment.databinding.ItemInnerFileBinding
import java.io.File
import java.io.FileFilter
import java.io.InputStream
import java.util.*

class FileAdapter(
    cb: FileDiff = FileDiff()
) : ListAdapter<File, FileViewHolder>(cb) {

    var needGrantPermission = true
        @SuppressLint("NotifyDataSetChanged")
        set(value) {
            if (field != value) {
                field = value
                notifyDataSetChanged()
            }
        }

    var selectedFiles = emptyList<File>()
        @SuppressLint("NotifyDataSetChanged")
        set(value) {
            field = value
            this.notifyDataSetChanged()
        }

    private var cb: OnItemClickCallback? = null
    fun setOnItemClick(callback: OnItemClickCallback) {
        cb = callback
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
        return ItemInnerFileBinding.inflate(LayoutInflater.from(parent.context), parent, false).run {
            FileViewHolder(this)
        }
    }

    override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
        holder.itemFileBinding.apply {
            val file = currentList[position]
            val rootDir = Environment.getExternalStorageDirectory()
            fileNameTx.text = if (file.path == rootDir.path) {
                "Internal Storage"
            } else {
                file.name
            }
            setDesc(fileDetailTx, file)
            fileIcon.setImageResource(getIcon(file))

            root.setOnClickListener {
                val index = holder.layoutPosition
                if (index in currentList.indices) {
                    it.postDelayed({
                        cb?.invoke(index)
                    }, 100)
                }
            }

            checkbox.visibility = if (file.isDir()) View.GONE else View.VISIBLE
            val iconRes =
                if (selectedFiles.contains(file)) R.drawable.ic_check else R.drawable.ic_uncheck
            checkbox.setImageResource(iconRes)
        }
    }

    private fun File.isDir(): Boolean {
        return isDirectory || this == root
    }

    /**
     * 计算文件大小
     */
    private fun getFileSizeString(context: Context, file: File): String {
        val isDefaultFirmware = file.path.contains("firmware/default")
        if (file.isDir()) {
            return "0B"
        }
        val byteCount = if (isDefaultFirmware) {
            val `in`: InputStream = context.resources.assets.open(file.path)
            //获取bai文du件的zhi字dao节内数容
            try {
                `in`.available()
            } catch (e: Exception) {
                0
            }.toLong()
        } else {
            file.length()
        }
        val KB = 1024
        val MB = 1024 * 1024
        val GB = 1024 * 1024 * 1024
        return when (byteCount) {
            in 0 until KB -> {
                "$byteCount" + "B"
            }
            in KB until MB -> {
                "${byteCount / KB}KB"
            }
            in MB until GB -> {
                "${byteCount / MB}MB"
            }
            else -> {
                "${byteCount / GB}GB"
            }
        }
    }

    /**
     * 获取对应图标资源
     */
    private fun getIcon(file: File): Int {
        return if (file.isDir()) {
            val childFileCount = getChildCount(file)
            if (childFileCount == 0) {
                R.drawable.ic_folder_empty
            } else {
                R.drawable.ic_folder
            }
        } else {
            when (file.extension.lowercase(Locale.ROOT)) {
                "bin" -> {
                    R.drawable.ic_ota_file
                }
                else -> {
                    R.drawable.ic_file
                }
            }
        }
    }

    private fun getChildCount(file: File): Int {
        return when {
            file == root -> 1
            file.isDir() -> file.listFiles(fileFilter)?.size ?: 0
            else -> 0
        }
    }

    private fun setDesc(descTx: TextView, file: File) {
        descTx.text = if (needGrantPermission) {
            descTx.setTextColor(Color.RED)
            "Please click me to grant app access to the file"
        } else {
            descTx.setTextColor(Color.LTGRAY)
            if (!file.isDir()) {
                getFileSizeString(descTx.context, file)
            } else {
                "${getChildCount(file)} items"
            }
        }
    }


}

class FileViewHolder(val itemFileBinding: ItemInnerFileBinding) :
    RecyclerView.ViewHolder(itemFileBinding.root)

class FileDiff : DiffUtil.ItemCallback<File>() {
    override fun areItemsTheSame(oldItem: File, newItem: File): Boolean {
        return oldItem.path == newItem.path
    }

    override fun areContentsTheSame(oldItem: File, newItem: File): Boolean {
        return oldItem.name == newItem.name
    }
}